<template>
	<u-popup :show="showPop" mode="bottom" border-radius="14" :closeable="true" @close="onClose" :safe-area-inset-bottom="true">
		<view class="goods_item_a">
			<view class="goods_item_a_a">
				<view class="goods_item_a_a_a">
					<custom-image class="goods_item_a_a_a" radius="10rpx" @tap="previewImage(checkedGoods.image)" :src="checkedGoods.image"></custom-image>
				</view>
				<view class="goods_item_a_a_b">
					<view class="goods_item_a_a_b_b">
						{{goods_info.name}}
					</view>
					<view class="goods_item_a_a_b_a">
						<view class="goods_item_a_a_b_aa" v-if="checkedGoods.price==0">
							积分{{checkedGoods.integral}}
						</view>
						<view class="goods_item_a_a_b_aa" v-if="checkedGoods.integral==0">
							¥{{checkedGoods.price}}
						</view>
						<view class="goods_item_a_a_b_aa" v-if="checkedGoods.integral>0 && checkedGoods.price>0">
						积分{{checkedGoods.integral}}+¥{{checkedGoods.price}}
						</view>
						<view class="goods_item_a_a_b_c">
							库存：{{checkedGoods.stock}}件
						</view>
					</view>
					<view class="goods_item_a_a_b_d">
						{{specValueText}}
					</view>
				</view>
			</view>
			<view class="goods_item_a_b">
				<scroll-view style="max-height: 600rpx;" scroll-y="true">
					<view class="goods_item_a_b_a" v-for="(item, index) in specList" :key="index">
						<view class="goods_item_a_b_a_a">
							<view class="goods_item_a_b_a_a_a">{{ item.name }}</view>
							<view class="goods_item_a_b_a_a_b">{{checkedGoods.spec_value_ids_arr[index] == '' ? '请选择'+item.name:''}}</view>
						</view>
						<view class="goods_item_a_b_a_b">
							<view :class="'goods_item_a_b_a_b_a ' +
								    ( checkedGoods.spec_value_ids_arr[index] == specitem.id ? 'checked' : '' ) + 
								    ( isDisable(specitem.id) ? 'disabled':'')"
								v-for="(specitem, index2) in item.spec_value" :key="index2" @click="choseSpecItem(index, index2)">
								{{ specitem.value }}
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
			<view class="goods_item_a_c">
				<view class="goods_item_a_c_a">数量选择</view>
				<view class="goods_item_a_c_b">
					<u-number-box v-model="goodsNum" input-height="66" :min="1" :max="checkedGoods.stock" :disabled="disabledNumberBox"></u-number-box>
				</view>
			</view>
			<view class="goods_item_a_d" :class="specValueText.indexOf('请选择') != -1 || checkedGoods.stock == 0 ? 'disabled':''">
				<button class="goods_item_a_d_a" v-if="!group" size="lg" @tap="onClick('addcart')">{{yellowBtnText}}</button>
				<button class="goods_item_a_d_a" v-if="group" size="lg" @tap="onClick('confirm')">{{redBtnText}}</button>
			</view>
		</view>
	</u-popup>
</template>

<script>
	export default {
		data() {
			return {
				checkedGoods: {
				    stock: 0
				}, //选中的
				outOfStock: [], //缺货的
				specList: [], //规格
				disable: [], //不可选择的
				goodsNum: 1,
				goods_info:[],
				showPop:false
			};
		},

		components: {},
		props: {
			show: {
				type: Boolean
			},
			goods: {
				type: Object
			},
			showAdd: {
				type: Boolean,
				default: true
			},
			goodsType: {
				type: String,
				default:'putong'
			},
			
			showConfirm: {
				type: Boolean,
				default: false
			},
			redBtnText: {
				type: String,
				default: "立即购买"
			},
			yellowBtnText: {
				type: String,
				default: "加入购物车"
			},
			group: {
				type: Boolean,
				default:0
			},
			isSeckill: {
				type: Boolean,
				default: false
			},
            showStock: {
                type: Boolean,
                default: true
            },
            disabledNumberBox: {
                type: Boolean,
                default: false
            },
            isBargain: {
                type: Boolean,
                default: false
            }
		},
		mounted() {},
		
		computed: {
		    // 选择的规格参数等
		    specValueText() {
		        let arr = this.checkedGoods.spec_value_ids?.split(',');
		        let spec_str = ''
		        if (arr)
		            arr.forEach((item, index) => {
		                if (item == '') spec_str += this.specList[index].name + ','
		            })
		        if (this.checkedGoods?.stock != 0 && spec_str == '')
		            return `已选择 ${this.checkedGoods.spec_value_str}`
		        else
		            return `请选择 ${spec_str.slice(0, spec_str.length - 1)}`
		    }
		},
		
		watch: {
		    goods(value) {
				this.specList = value.goods_spec || [];
		        this.goods_info = value || [];
		        let goodsItem = value.goods_item || [];
		        this.outOfStock = goodsItem.filter(item => item.stock == 0)
		        // 找出库存不为0的
		        const resultArr = goodsItem.filter(item => item.stock != 0)
		        if (resultArr.length != 0) {
		            resultArr[0].spec_value_ids_arr = resultArr[0].spec_value_ids.split(',');
		            this.checkedGoods = resultArr[0]
		        } else {
		            // 无法选择
					goodsItem[0].spec_value_ids_arr = []
					
		            this.disable = goodsItem.map(item => item.spec_value_ids.split(','));
		            this.checkedGoods = goodsItem[0]
		        }
		    },
		
		    specList(value) {
		        if (this.checkedGoods.stock == 0) return
		
		        const res = this.goods.goods_item.filter(item => {
		            return this.checkedGoods.spec_value_ids === item.spec_value_ids
		        })
		
		        // 库存为0的规格
		        const idsArr = this.checkedGoods.spec_value_ids_arr;
		        const outOfStock = this.outOfStock;
		        // 找出规格相同和规格不相同的余数
		        const getArrGather = this.getArrResult(idsArr, outOfStock);
		        // 计算出缺货的规格项
		        this.disable = this.getOutOfStockArr(getArrGather, idsArr)
		
		        if (res.length != 0) {
		            let result = JSON.parse(JSON.stringify(res[0]))
		            result.spec_value_ids_arr = result.spec_value_ids.split(',')
		            this.checkedGoods = result;
		            // 同步到父组件
		            this.$emit('change', {
		                detail: this.checkedGoods
		            });
		        }
		    },
		
		    show(val) {
		        this.showPop = val
		    }
		
		},
		created() {
		    
		},
		methods: {
		    isDisable(e) {
		        const res = this.disable.filter(item => item == e)
		        if (res.length != 0) return true
		        else return false
		    },
		
		    onClose() {
		        this.$emit('close')
		    },
		
		    onClick(type) {
		        let {
		            checkedGoods,
		            goodsNum
		        } = this;
		        if(this.specValueText.indexOf('请选择') != -1){
					uni.showToast({
					    title: this.specValueText,
						icon:"none",
					    duration: 2000
					});
					return
				}
		        if(checkedGoods.stock == 0){
					uni.showToast({
					    title:'当前选择库存不足',
						icon:"none",
					    duration: 2000
					});
					return
				}
		        checkedGoods.goodsNum = goodsNum;
		        this.$emit(type, {
		            detail: checkedGoods
		        });
		    },
		
		    // 选择规格
		    choseSpecItem(index, index2) {
		        const id = this.specList[index].spec_value[index2].id;
		        // 无法选择
		        const disable = this.disable.filter(item => item == id)
		        if (disable.length != 0) return
		
		        let idsArr = this.checkedGoods.spec_value_ids_arr;
		        if (id == idsArr[index]) idsArr[index] = ''
		        else idsArr[index] = id;
		        //保存已选规格
		        this.checkedGoods.spec_value_ids_arr = idsArr;
		        this.checkedGoods.spec_value_ids = idsArr.join(',');
				console.log(this.checkedGoods);
		        // 重新渲染页面
		        this.specList = [...this.specList]
		    },
		
		    // 过滤出需要进行禁用的规格
		    getOutOfStockArr(arr, arr1, result = []) {
		        arr.forEach(el => {
		            if (el.num >= (arr1.length - 1)) {
		                result.push(...el.different)
		            }
		        })
		        return result
		    },
		
		    // 匹配出缺货库存和已选中对比结果
		    getArrIdentical(arr1, arr2, arr = [], num = 0) {
		        arr1.forEach(el => {
		            arr2.forEach(el2 => {
		                if (el == el2) {
		                    num += 1;
		                    arr.push(el)
		                }
		            })
		        });
		        return {
		            num, //n个相同的
		            different: this.getArrDifference([...new Set(arr)].map(Number), arr2.map(Number)),
		            identical: [...new Set(arr)]
		        }
		    },
		
		    // 匹配出已选择和缺库存的
		    getArrResult(arr, outOfStock, result = []) {
		        outOfStock.forEach(item => {
		            const res = this.getArrIdentical(arr, item.spec_value_ids.split(','))
		            if (res != undefined && res.length != 0) {
		                result.push(res)
		            }
		        })
		        return result
		    },
		
		    // 找出两个数组中参数不同的
		    getArrDifference(arr1, arr2) {
		        return arr1.concat(arr2).filter(function(v, i, arr) {
		            return arr.indexOf(v) == arr.lastIndexOf(v);
		        });
		    },
		    // 查看商品图片
		    previewImage(current) {
		        uni.previewImage({
		            current,
		            urls: [current] // 需要预览的图片http链接列表
		        });
		    }
		
		}
	};
</script>
<style lang="scss" scoped>
	.goods_item_a{
		width: 750rpx;
		padding: 65rpx 30rpx;
		border-radius: 20rpx 20rpx 0 0;
	}
	.goods_item_a_a{
		height: 250rpx;
		overflow: hidden;
		border-bottom: 1rpx solid #EFEFEF;
	}
	.goods_item_a_a_a{
		width: 200rpx;
		height: 200rpx;
		background: #FFF2DE;
		border-radius: 5rpx;
		float: left;
	}
	.goods_item_a_a_b{
		float: left;
		margin-left: 24rpx;
		width: 450rpx;
	}
	.goods_item_a_a_b_a{
		font-size: 36rpx;
		font-family: PingFang SC;
		font-weight: bold;
		color: #E71102;
		overflow: hidden;
		margin-top: 20rpx;
	}
	.goods_item_a_a_b_b{
		font-size: 32rpx;
		font-family: PingFang SC;
		font-weight: 800;
		color: #000000;
		height: 90rpx;
		overflow: hidden;
	}
	.goods_item_a_a_b_aa{
		float: left;
	}
	.goods_item_a_a_b_c{
		font-size: 24rpx;
		font-family: Microsoft YaHei;
		font-weight: 400;
		color: #666666;
		float: right;
		line-height: 40rpx;
	}
	.goods_item_a_a_b_d{
		font-size: 24rpx;
		font-family: Microsoft YaHei;
		font-weight: 400;
		color: #666666;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		margin-top: 10rpx;
	}
	.goods_item_a_b{
		overflow: hidden;
	}
	.goods_item_a_b_a{
		margin-top: 40rpx;
		border-bottom: 1rpx solid #EEEEEE;
	}
	.goods_item_a_b_a_a{
		font-size: 28rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #333333;
		overflow: hidden;
		margin-bottom: 30rpx;
	}
	.goods_item_a_b_a_a_a{
		float: left;
		font-size: 26rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #333333;
	}
	.goods_item_a_b_a_a_b{
		margin-left: 20rpx;
		color: red;
		float: left;
	}
	.goods_item_a_b_a_b{
		overflow: hidden;
	}
	.goods_item_a_b_a_b_a{
		padding:16rpx;
		background: #FFFFFF;
		border: 2px solid #DCDCDC;
		border-radius: 32rpx;
		float: left;
		margin-right: 20rpx;
		margin-bottom:20rpx;
		min-width: 100rpx;
		text-align: center;
	}
	.goods_item_a_b_a_b_a.checked{
		background: #FFF3EC;
		border: 2px solid #E71102;
		border-radius: 32rpx;
		color: #E71102;
	}
	.goods_item_a_b_a_b_a.disabled{
		background: #F4F4F4;
		color: #BEBEBE;
	}
	.goods_item_a_c{
		height: 66rpx;
		overflow: hidden;
		margin-top: 40rpx;
	}
	.goods_item_a_c_a{
		height: 66rpx;
		line-height: 80rpx;
		font-size: 26rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #333333;
		float: left;
	}
	.goods_item_a_c_b{
		float: right;
	}
	.goods_item_a_e{
		font-size: 24rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #E71102;
		margin-top: 20rpx;
	}
	.goods_item_a_d{
		width: 702rpx;
		height: 80rpx;
		margin: auto;
		margin-top: 60rpx;
	}
	.goods_item_a_d_a{
		width: 468rpx;
		height: 88rpx;
		background: #E71102;
		border-radius: 44rpx;
		font-size: 30rpx;
		font-family: PingFang SC;
		font-weight: 800;
		color: #FFFFFF;
		line-height: 88rpx;
		text-align: center;
		margin: auto;
	}
	.goods_item_a_d_b{
		width: 246rpx;
		background: #E71102;
		border-radius: 40rpx;
		font-size: 32rpx;
		font-family: PingFang SC;
		font-weight: bold;
		color: #FFFFFF;
		line-height: 80rpx;
		text-align: center;
		border: 0 !important;
		float: left;
		margin-left:60rpx;
	}
	.goods_item_a_d.disabled .goods_item_a_d_a,.goods_item_a_d.disabled .goods_item_a_d_b{
		background: #F4F4F4;
		color: #BEBEBE;
	}
</style>